﻿using System;
using System.Linq;
using Autofac;
using Autofac.Core;
using Autofac.Core.Activators.Reflection;

namespace Freedom.Common.Autofac
{
    public static class ComponentTypeHelper
    {
        public static Type GetComponentTypeByKey(this IContainer container, object key, Type type)
        {
            var registration = container.ComponentRegistry.RegistrationsFor(new KeyedService(key, type)).SingleOrDefault();
            if (registration != null)
            {
                var activator = registration.Activator as ReflectionActivator;
                if (activator != null)
                {
                    //we can get the type
                    return activator.LimitType;
                }
            }

            return null;
        }
    }
}
